package myJs.cps

import myJs.cps.Style
import myJs.myPkg.reactHookForm._
import org.scalajs.dom.html.Input
import org.scalajs.dom.{Event, html}
import slinky.core.annotations.react
import slinky.core.facade.Fragment
import slinky.core.facade.Hooks.useEffect
import slinky.core.{FunctionalComponent, SyntheticEvent, TagElement}
import slinky.web.html._

import scala.scalajs.js

/**
 * Created by yz on 3/11/2020
 */
@react object PureInputCp {

  case class Props(
                    useForm: UseFormRT,
                    name: String,
                    readOnly: Boolean = false,
                    required: Boolean = true,
                    registerOptions: RegisterOptions = RegisterOptions(),
                    onChange: js.UndefOr[String => Unit] = js.undefined,
                    showValidate: Boolean = true,
                    value: String = "",
                    width: String = "",
                  )


  val component = FunctionalComponent[Props] { props =>

    object FTool {

    }

    useEffect(() => {
      props.useForm.setValue(props.name, props.value)
      props.useForm.trigger(props.name)
    }, List(props.value)
    )

    Fragment(
      Controller(
        name = props.name,
        control = props.useForm.control,
        rules = props.registerOptions,
        render = (fieldR: FieldR) => {
          val field = fieldR.field
          input(
            style := Style(width = props.width),
            className := "form-control",
            name := field.name,
            value := props.value,
            onChange := { (e: SyntheticEvent[TagElement#RefType, Event]) => {
              val v = e.target.asInstanceOf[html.Input].value
              field.onChange(e)
              props.onChange.foreach(_ (v))
            }
            },
            ref := field.ref,
            readOnly := props.readOnly
          )()
        }
      ),
      if (props.showValidate && props.useForm.formState.errors.isDefinedAt(props.name)) {
        small(className := "help-block", props.useForm.formState.errors(props.name).message)
      } else null
    )


  }

}



